package rgbos.forum.serverClient;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import rgbos.forum.domain.*;
import rgbos.forum.persistance.Persistance;


public class ForumServer implements Runnable {
	int portNum_;
	ServerSocket serverSocket_;
	private ForumCtrlUser fcUser_;
	private ForumCtrlPost fcPost_;
	private ForumCtrlTopic fcTopic_;
	private Persistance pers_;
	private ControlFacade facade_;
	
	public ForumServer(int portNum) {
		this.portNum_ = portNum;
		this.serverSocket_ = null;
		pers_  = new Persistance("SQL");
		pers_.connect();
		this.fcUser_ = new ForumCtrlUser(pers_);
		this.fcPost_ = new ForumCtrlPost(pers_);
		this.fcTopic_ = new ForumCtrlTopic(pers_);
		this.facade_ = new ControlFacade(fcUser_,fcPost_,fcTopic_);

	}

	public ControlFacade getFacade(){
		return this.facade_;
	}

	public void run() {
		try {
			this.serverSocket_ = new ServerSocket(this.portNum_);
		} catch (IOException e) {
			Auditor.Log("cant open server socket", this.getClass());
			e.printStackTrace();
		}
		Socket accepted = null;		
		while (true)	{
			try {
				accepted = this.serverSocket_.accept();
			} catch (IOException e) {
				Auditor.Log("problem with serverSocket ",this.getClass());
				e.printStackTrace();
			}
			Auditor.Log("got new connection on " + accepted.getInetAddress(), this.getClass());
			ClientHandler ch = new ClientHandler(accepted,this.facade_);
			ch.start();
		}

	}
}
